import 'package:flutter/widgets.dart';
import 'package:mobile_app.core/core/application/models/app_navigator_page_model.dart';
import 'package:mobile_app.core/core/presentation/widgets/app_navigator_page.dart';

class AppNavigatorObserver extends NavigatorObserver {
  AppNavigatorObserver({
    required this.onPageAddedToNavigator,
    required this.onPageRemovedFromNavigator,
  });

  void Function(AppNavigatorPageModel pageModel) onPageAddedToNavigator;
  void Function(AppNavigatorPageModel pageModel) onPageRemovedFromNavigator;

  @override
  void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
    final pageModel = _getRoutePageModel(route);

    if (pageModel != null) {
      onPageAddedToNavigator(pageModel);
    }
  }

  @override
  void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) async {
    final pageModel = _getRoutePageModel(route);

    if (pageModel != null) {
      if (route is TransitionRoute ) {
        await route.completed;
      }

      onPageRemovedFromNavigator(pageModel);
    }
  }

  @override
  void didRemove(Route<dynamic> route, Route<dynamic>? previousRoute) async {
    final pageModel = _getRoutePageModel(route);

    if (pageModel != null) {
      if (route is TransitionRoute ) {
        await route.completed;
      }

      onPageRemovedFromNavigator(pageModel);
    }
  }

  AppNavigatorPageModel? _getRoutePageModel(Route<dynamic> route) {
    if (route.settings is! AppNavigatorPage) {
      return null;
    }

    final page = route.settings as AppNavigatorPage;

    return page.pageModel;
  }
}
